package cn.lger.service;

import cn.lger.dao.AdminDao;
import cn.lger.encoder.PasswordEncoder;
import cn.lger.pojo.Administrator;
import cn.lger.pojo.Page;
import cn.lger.util.PageUtil;
import cn.lger.util.StringEmptyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Code that Changed the World
 *
 * @author Pro
 * @date 2018-06-17.
 */

@Service
public class AdminService {

    @Resource
    private AdminDao adminDao;
    @Resource
    private PasswordEncoder encoder;

    public Administrator findOneByUsernameAndPassword(String username, String password) {
        Administrator administrator = adminDao.findOneByUsername(username);
        if (encoder.matches(password, administrator.getPassword())) {
            return administrator;
        } else {
            return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public int insertOne(Administrator admin) {
        String code = encoder.encoder(admin.getPassword());
        admin.setPassword(code);
        return adminDao.insertOne(admin);
    }

    @Transactional(rollbackFor = Exception.class)
    public int update(Administrator admin) {

        boolean isModify = false;

        if (StringEmptyUtil.notEmpty(admin.getPassword())) {
            isModify = true;
            admin.setPassword(encoder.encoder(admin.getPassword()));
        }

        if (StringEmptyUtil.notEmpty(admin.getEmail())) {
            isModify = true;
        }

        if (isModify) {
            return adminDao.updateOne(admin);
        } else {
            return 0;
        }

    }

    public Page<Administrator> findOnePage(Integer currentPage, Integer size) {
        Page<Administrator> page = PageUtil.generator(currentPage, size);
        page.setContent(adminDao.findOnePage(page.getPage(), page.getSize()));
        page.setCount(adminDao.getTotal());
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    public int deleteOneById(int id) {
        return adminDao.deleteOneById(id);
    }

    public int checkUsername(String username) {
        return adminDao.checkUsername(username);
    }
}



